import cv2
import math
import numpy as np
import random

# 读取图片
image_path = "edge/crop_112.png"
target = cv2.imread(image_path)

temp = target.copy()
# 识别纯黑像素（RGB 约为 (0,0,0)）
black_pixels = np.all(temp == [0, 0, 0], axis=-1)
# 将纯黑像素替换为纯白
temp[black_pixels] = [255, 255, 255]
cv2.imshow("xxxx",temp)

gray = cv2.cvtColor(temp, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (11, 11), 0)
edge = cv2.Canny(blurred, 30, 90)
lines = cv2.HoughLinesP(edge, 1, np.pi / 180, 5, minLineLength=400, maxLineGap=50)

print(lines)

max_distance = 0
for line in lines:
    x1, y1, x2, y2 = line[0]
    distance = math.sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))
    if distance > max_distance:
        max_distance = distance
        longest = line[0]
x1, y1, x2, y2 = longest
mid_y, mid_x = int((x1 + x2) / 2), int((y1 + y2) / 2)
print("position:", mid_x, mid_y)
rand_offset = random.randint(20, 40)
if math.fabs(x2 - x1) > math.fabs(y2 - y1):
    # print('--', gray[int(mid_x/2), mid_y], gray[int((mid_x + 640)/2), mid_y])
    if gray[int(mid_x / 2), mid_y] < gray[int((mid_x + 640) / 2), mid_y]:  # 上背景下瓷砖
        pos_y, pos_x = int((x1 + x2) / 2) + rand_offset, int((y1 + y2) / 2)
    else:  # 上瓷砖下背景
        pos_y, pos_x = int((x1 + x2) / 2) - rand_offset, int((y1 + y2) / 2)
else:
    # print('|', gray[mid_x, int(mid_y / 2)], gray[mid_x, int((mid_y + 640) / 2)])
    if gray[mid_x, int(mid_y / 2)] < gray[mid_x, int((mid_y + 640) / 2)]:  # 左背景右瓷砖
        pos_y, pos_x = int((x1 + x2) / 2), int((y1 + y2) / 2) + rand_offset
    else:
        pos_y, pos_x = int((x1 + x2) / 2), int((y1 + y2) / 2) - rand_offset

pos_y, pos_x = int((x1 + x2) / 2), int((y1 + y2) / 2)
print('mid line pos:', pos_x, pos_y)
cv2.line(target, (x1, y1), (x2, y2), (100, 200, 100), 2)
cv2.circle(target, (pos_y, pos_x), 20, (0, 255, 255), 3)
gray_rgb = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB)
edge_rgb = cv2.cvtColor(edge, cv2.COLOR_GRAY2RGB)
# three = np.hstack((gray_rgb, edge_rgb, target))
# cv2.imshow('gray/edge/img', three)
# cv2.imshow("gray_rgb",gray_rgb)
cv2.imshow("edge_rgb",edge_rgb)
cv2.imshow("target",target)
cv2.waitKey()
cv2.destroyAllWindows()
